package com.banmoon.sync;

/**
 * 死锁示例
 */
public class DeadLock {

    public static void main(String[] args) {
        Thread threadA = new Thread(new ThreadA(), "ThreadA");
        Thread threadB = new Thread(new ThreadB(), "ThreadB");
        threadA.start();
        threadB.start();
    }

}

class ThreadA implements Runnable{

    @Override
    public void run() {
        synchronized (ThreadA.class){
            System.out.println(Thread.currentThread().getName() + "已持有锁：ThreadA");
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (ThreadB.class){
                System.out.println(Thread.currentThread().getName() + "已持有锁：ThreadA");
            }
        }
    }
}

class ThreadB implements Runnable{

    @Override
    public void run() {
        synchronized (ThreadB.class){
            System.out.println(Thread.currentThread().getName() + "已持有锁：ThreadB");
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (ThreadA.class){
                System.out.println(Thread.currentThread().getName() + "已持有锁：ThreadA");
            }
        }
    }
}